<?php
namespace Model;

class RegisterHandler {

	private $m_database = null;
	const PASSWORD_MISSMATCH = 0;
	const FIELDS_EMPTY = 1;
	const USERNAME_IN_USE = 2;
	const PASSWORD_WRONG_FORMAT = 3;
	const REG_SUCCESS = 4;

	public function __construct($a_database) {
		$this -> m_database = $a_database;
	}

	//Funktion för att registrera användare
	public function RegisterUser($username, 
								$firstname, 
								$lastname, 
								$socnr, 
								$address, 
								$address2, 
								$zip, 
								$town, 
								$phone, 
								$email, 
								$password, 
								$password2) {
		if (isset($username) && isset($password) && isset($password2)) {

			//kollar om båda lösenorden stämmer med varandra
			if ($password != $password2) {
				return self::PASSWORD_MISSMATCH;
			}
			//kollar så att fälten inte är tomma
			if ($username == '' || $password == '') {
				return self::FIELDS_EMPTY;
			}
			//kollar om användarnamnet är tillgängligt
			if ($stmt = $this -> m_database -> SqlStatement('SELECT User_Id, UserName, PassWord FROM users WHERE username = ?')) {

				$stmt -> bind_param('s', $username);

				$stmt -> execute();

				$stmt -> bind_result($dbUserid, $dbUsername, $dbPassword);

				while ($stmt -> fetch()) {
					if ($username == $dbUsername) {
						$stmt -> close();
						return self::USERNAME_IN_USE;
					}
				}

				$stmt -> close();
			}

			$vd = new \Common\Validator();
			//validerar användarnamn och lösenord och sedan registrerar användare
			if ($vd -> validateUsername($username) && $vd -> validatePassword($password)) {
				if ($stmt = $this -> m_database -> SqlStatement('INSERT INTO users (UserName, PassWord, FirstName, LastName, SocNr, Address, Address2, Town, ZipCode, PhoneNumber, eMail ) VALUES (?,?,?,?,?,?,?,?,?,?,?)')) {
					$password = md5($password2);
					$stmt -> bind_param('ssssssssiss', $username, $password, $firstname, $lastname, $socnr, $address, $address2, $town, $zip, $phone, $email);

					$stmt -> execute();

					$stmt -> close();

					return self::REG_SUCCESS;
				}
			}
			return self::PASSWORD_WRONG_FORMAT;
		}

	}

	//Tar bort en användare
	public function DeleteUser($username) {
		if (isset($username)) {
			if ($stmt = $this -> m_database -> SqlStatement('DELETE FROM users WHERE username = ?')) {
				$stmt -> bind_param('s', $username);

				$stmt -> execute();

				$stmt -> close();
				return true;
			}
		}

		return false;
	}

}
